<?php


namespace Modules\Common\Lib\Novel;


class QugeNovel implements Index
{
    private $baseUrl = "https://m.quge3.com";
    public function getList(int $sortId,int $page){
        $url = $this->baseUrl . "/json?sortid={$sortId}&page={$page}";
        $res = $this->httpRequest($url);
        if(!$res["body"]){
            return [
                'status'=>0,
                'message'=>"获取列表失败或没有数据url={$url}"
            ];
        }
        $list = json_decode($res["body"],true);
        if(!count($list)){
            return [
                'status'=>0,
                'message'=>"获取列表失败或没有数据url={$url}"
            ];
        }
        return [
            "status"=>1,
            "list"=>$list
        ];
    }
    public function getDescription(string $ext){
        $url = $this->baseUrl . $ext;
        $res = $this->httpRequest($url);
        preg_match_all("/<dd>(.*?)<\/dd>/",$res["body"],$matches);
        return [
            "status"=>1,
            "description"=>str_replace("展开全部&gt;&gt;","",strip_tags($matches[0][0]))
        ];
    }
    public function getChapter(string $ext){
        $url = $this->baseUrl . $ext . "list.html";
        $arrContextOptions = [
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false,
            ]
        ];
        $res = file_get_contents($url,false,stream_context_create($arrContextOptions));
        preg_match_all("/<dd>(.*?)<\/dd>/",$res,$matches);
        if(!isset($matches[0]) || count($matches[0]) < 2){
            return [
                'status'=>0,
                'message'=>"获取列表失败或没有数据url={$url}"
            ];
        }
        unset($matches[0][0]);
        $list = [];
        foreach ($matches[0] as $k=>$v){
            $str = str_replace("</a></dd>","",str_replace('<dd><a href ="',"",$v));
            $info = explode('">',$str);
            $list[$k] = [
                "name"=>$info[1],
                "url"=>$info[0]
            ];
        }
        if(!count($list)){
            return [
                'status'=>0,
                'message'=>"获取列表失败或没有数据url={$url}"
            ];
        }
        return [
            'status'=>1,
            'list'=>$list
        ];
    }

    public function getChapterInfo(string $name,string $url){
        $chapterUrl = $this->baseUrl . $url;
//        $chapterRes = $this->httpRequest($chapterUrl);
        $arrContextOptions = [
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false,
            ]
        ];
        $res = file_get_contents($chapterUrl,false,stream_context_create($arrContextOptions));
        preg_match_all("/<div id=\"chaptercontent\" class=\"Readarea ReadAjax_content\">(.*?)<\/div>/ism",$res,$chapterMatches);
        if(isset($chapterMatches[0]) && isset($chapterMatches[0][0])){
            return [
                "status"=>1,
                "info"=>[
                    "name"=>$name,
                    "content"=>$chapterMatches[0][0]
                ]
            ];
        }else{
            return [
                "status"=>0,
                'message'=>"获取列表失败或没有数据url={$chapterUrl}"
            ];
        }
    }

    private function httpRequest($url, $data = null, $cookieFile = false, $headers = false, $proxy = false, $outTime = 5)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            if (is_array($data)) {
                curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
            } else {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
        }
        if ($cookieFile) {
            curl_setopt($curl, CURLOPT_COOKIEJAR, $cookieFile);
            curl_setopt($curl, CURLOPT_COOKIEFILE, $cookieFile);
        }
        if (is_array($headers)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        if (is_array($proxy)) {
            curl_setopt($curl, CURLOPT_PROXY, $proxy['ip']);
            curl_setopt($curl, CURLOPT_PROXYPORT, $proxy['port']);
        } else if (is_string($proxy)) {
            curl_setopt($curl, CURLOPT_PROXY, $proxy);
        }
        curl_setopt($curl, CURLOPT_MAXREDIRS, 3);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_TIMEOUT, $outTime);
        curl_setopt($curl, CURLOPT_HEADER, true);
        curl_setopt($curl, CURLINFO_HEADER_OUT, true);
        $response = curl_exec($curl);
        $curlInfo = curl_getinfo($curl);
        $header = substr($response, 0, $curlInfo['header_size']); // 根据头大小获取头信息
        $body = substr($response, $curlInfo['header_size']);

        curl_close($curl);
        return [
            'header' => $header,
            'body' => $body,
//            'request_header' => $curlInfo['request_header'],
            'url'=>$url
        ];
    }


}
